package com.fable.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.fable.biz.operate.AdminUserService;
import com.fable.common.utils.JsonResult;
import com.fable.dal.dto.AdminUserDTO;
import com.fable.dal.model.AdminDO;
import com.fable.dal.model.AdminUserDO;
import com.fable.utils.GeetestLib;
import com.fable.utils.StringUtil;
import com.fable.utils.WebUtil;
import com.fable.web.common.admin.UserTools;
import com.fable.web.common.annotation.Track;
import com.fable.web.common.geetest.GeetestConfig;
import com.fable.web.page.P;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.UUID;

@Controller
public class LoginController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    AdminUserService adminUserService;

    @Value("${fable.service.url}")
    private String fableServiceUrl;

    @Value("${audi.service.login.url}")
    private String audiServiceLoginUrl;

    @Value("${fable.env}")
    private String env;


    @RequestMapping("/login.htm")
    @Track(tag = P.UrlEnum.login)
    public String login(ModelMap model, String chrome, String redirectURL) {
        model.put("redirectURL", redirectURL);
        model.put("chrome", chrome);
        model.put("url", fableServiceUrl);

//        if (UserTools.getAdmin() != null) {
//            return P.Common.center;
//        }
        return P.Common.login;
    }

    @RequestMapping("/login.json")
    @Track(tag = P.UrlEnum.loginJson)
    @ResponseBody
    public JsonResult doLogin(ModelMap model, HttpServletRequest request, HttpSession session) {
        JsonResult result = new JsonResult();
        String userName = request.getParameter("userName");
        String passWord = request.getParameter("passWord");
        String redirectURL = request.getParameter("redirectURL");
        if (StringUtil.isBlank(userName) || StringUtil.isBlank(passWord)) {
            if (UserTools.getAdmin() != null) {
                return result;
            } else {
                result.setErrMsg("请重新登陆");
                return result;
            }
        } else {
            GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key(),
                    GeetestConfig.isnewfailback());

            String challenge = request.getParameter(GeetestLib.fn_geetest_challenge);
            String validate = request.getParameter(GeetestLib.fn_geetest_validate);
            String seccode = request.getParameter(GeetestLib.fn_geetest_seccode);
            int gtResult = 0;
            //从session中获取gt-server状态
            int gt_server_status_code = (Integer) request.getSession().getAttribute(gtSdk.gtServerStatusSessionKey);

            String userId = (String) request.getSession().getAttribute("userid");
            //自定义参数,可选择添加
            HashMap<String, String> param = new HashMap<String, String>();
//            param.put("user_id", userId); //网站用户id
            param.put("client_type", "web"); //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
            param.put("ip_address", WebUtil.getIpAddr(request)); //传输用户请求验证时所携带的IP

            if (gt_server_status_code == 1) {
                //gt-server正常，向gt-server进行二次验证
                gtResult = gtSdk.enhencedValidateRequest(challenge, validate, seccode, param);
                logger.debug("极验服务正常，向gt-server进行二次验证,userName:{},password:{}", userName, passWord);
            } else {
                // gt-server非正常情况下，进行failback模式验证
                logger.warn("极验服务异常,进行failback模式验证,use your own server captcha validate");
                gtResult = gtSdk.failbackValidateRequest(challenge, validate, seccode);
                logger.info("极验服务异常,failback模式验证结果,gtResult:{},userName:{},password:{}", JSON.toJSONString(gtResult), userName, passWord);
            }
            if (gtResult == 1) {
                //验证登陆名和密码
                AdminUserDTO adminUserDTO = adminUserService.login(userName, passWord);
                if (adminUserDTO != null) {
                    UserTools.setCurrentUser(session, adminUserDTO);
                    if (StringUtil.isNotBlank(redirectURL) && !"/".equals(redirectURL) & !getSite().equals(redirectURL)) {
                        result.setData(redirectURL);
                        return result;
                    } else {
                        return result;
                    }
                } else {
                    result.setCustomErrCode("-1", "用户名或密码错误!");
                    return result;
                }
            } else {
                result.setCustomErrCode("-2", "验证码错误,请刷新重试!");
                return result;
            }
        }
    }

    @RequestMapping("/loginOut.htm")
    @Track(tag = P.UrlEnum.loginOut)
    public String doLoginOut(HttpSession session) {
        UserTools.removeCurrentUser(session);
        return P.Common.login;

    }

    private String getSite() {
        return fableServiceUrl + "index.htm";
    }


}